import React, { useState, useEffect, useRef } from 'react'
import { Modal, Form, Tabs, Input, Button, Checkbox, Select, Row, Col, message, Spin } from 'antd';
import { setStore, getStore } from '@/utils/commons'
import VerifyBox from '@/components/verifyBox'
import API from '@/api/api'
import Funs from '@/utils/Funs'
import './index.scss';

const { TabPane } = Tabs;
const { Option } = Select;

function Register(props) {
    const [registerStatus, setRegisterStatus] = useState(false)
    const [load, setLoad] = useState(false)
    const [timer, setTimer] = useState(0)
    const [phoneArea, setPhoneArea] = useState('86')
    const [registerType, setRegisterType] = useState('phone')
    const [phoneForm] = Form.useForm();
    const [emailForm] = Form.useForm();
    const verifyRef = useRef();

    useEffect(() => {
        let interval;
        if (timer > 0) {
            interval = setInterval(() => {
                setTimer(timer - 1);
            }, 1000);
        }
        return () => clearInterval(interval);
    }, [timer]);

    const tabChange = (e) => {
        setRegisterType(e)
        emailForm.resetFields();
        phoneForm.resetFields();
        phoneForm.setFieldsValue({ phoneArea: '86' })
    }

    const cancelModal = () => {
        props.close()
    }

    const toLogin = () => {
        props.toLogin()
    }

    const onFinish = async (values) => {
        let opts = { password: values.password, captcha: values.captchaCode, inviteCode: values.inviteCode }
        if (registerType === 'phone') {
            opts.phone = values.phone
            opts.phoneArea = values.phoneArea
        } else {
            opts.email = values.email
        }

        setLoad(true)
        let res = await API.register(opts)
        try {
            if (res) {
                message.success('注册成功');
                let userInfo = res.data || "";
                let token = {
                    data: res.data.token,
                    time: new Date().getTime()
                }
                setLoad(false)
                setStore('userInfo', JSON.stringify(userInfo))
                setStore('token', JSON.stringify(token))
                window.location.reload()
            } else {
                setLoad(false)
            }
        } catch (err) {
            setLoad(false)
        }
    }



    const showVerify = async () => {
        if (registerType === 'phone') {
            const fileds = await phoneForm.validateFields(['phone'])
            if (!Funs.isPhone(fileds.phone)) { return false }
            openVerifyModal()
        } else if (registerType === 'email') {
            const fileds = await emailForm.validateFields(['email'])
            if (!Funs.isEmail(fileds.email)) { return false }
            openVerifyModal()
        } else {
            return false
        }
    }

    const cancelVerifyModal = () => {
        verifyRef.current.cancelModal()
    }

    const openVerifyModal = () => {
        verifyRef.current.openModal()
    }

    const sendCaptcha = async (captcha, key) => {
        let opts = { action: 'register', type: registerType, captcha: captcha, captchaKey: key };
        if (registerType === 'phone') {
            const fileds = await phoneForm.validateFields(['phone', 'phoneArea'])
            opts.phone = fileds.phone
            opts.phoneArea = fileds.phoneArea
        } else {
            const fileds = await emailForm.validateFields(['phone', 'phoneArea', 'email'])
            opts.email = fileds.email
        }

        if (!captcha) {
            message.warning('请输入图形验证码')
            return false
        }

        if (timer === 0) {
            let sendCaptchaRes = await API.sendVerify(opts);
            if (sendCaptchaRes) {
                setTimer(60)
                message.success("已成功发送验证码");
                cancelVerifyModal()
            }
        } else {
            message.warning("验证码发送间隔太短，请稍后再试")
        }
    }

    const prefixSelector = (
        <Form.Item name="phoneArea" noStyle>
            <Select style={{ width: 80 }} className="register-select">
                {
                    props.phoneAreaList && Object.values(props.phoneAreaList).map((value, index) => {
                        return <Option value={value.code} key={index}>+{value.code}</Option>
                    })
                }
            </Select>
        </Form.Item>
    );

    const buttonAfter = (
        <a className="captcha-btn" onClick={showVerify}> {timer === 0 ? '发送验证码' : timer + '秒'}</a>
    )

    return (
        <Modal className="register" visible={props.status} onCancel={cancelModal} footer={null}>
            {
                !load ? null :
                    <div className="load-mark">
                        <Spin />
                    </div>
            }
            <Tabs defaultActiveKey={registerType} size="large" onChange={tabChange}>
                <TabPane tab="手机注册" key="phone">
                    <Form
                        form={phoneForm}
                        className="register-form"
                        onFinish={onFinish}
                        initialValues={{
                            phoneArea: phoneArea
                        }}
                    >
                        <Form.Item name="phone" rules={[
                            { required: true, message: '请输入手机号码' },
                            { pattern: new RegExp(/^1(?:70\d|(?:9[89]|8[0-24-9]|7[135-8]|66|5[0-35-9])\d|3(?:4[0-8]|[0-35-9]\d))\d{7}$/), message: "输入手机号码格式有误" }
                        ]}>
                            <Input className="register-input" placeholder="请输入手机" addonBefore={prefixSelector} bordered={false} />
                        </Form.Item>
                        <Form.Item name="password" rules={[
                            { required: true, message: '请输入密码', },
                            { pattern: new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{8,}$/i), message: "密码最低8位英文数字组成" }
                        ]}>
                            <Input.Password className="register-input" placeholder="请输入密码" bordered={false} />
                        </Form.Item>
                        <Form.Item name="passwordRetype" rules={[
                            { required: true, message: '请再次输入密码' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}>
                            <Input.Password className="register-input" placeholder="再输入密码" bordered={false} />
                        </Form.Item>
                        <Form.Item name="captchaCode" rules={[
                            { required: true, message: '输入验证码' }
                        ]}>
                            <Input className="register-input" placeholder="输入验证码" suffix={buttonAfter} bordered={false} />
                        </Form.Item>
                        <Form.Item name="inviteCode">
                            <Input className="register-input" placeholder="输入邀请码(非必选)" bordered={false} />
                        </Form.Item>
                        <Form.Item >
                            <Button type="primary" htmlType="submit" className="register-form-button">
                                立即注册
                            </Button>
                        </Form.Item>
                    </Form>
                </TabPane>
                <TabPane tab="邮箱注册" key="email">
                    <Form
                        form={emailForm}
                        className="register-form"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                    >
                        <Form.Item name="mail" rules={[
                            { required: true, message: '请输入邮箱', },
                            { pattern: new RegExp(/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/), message: "邮箱格式有误" }
                        ]}>
                            <Input className="register-input" placeholder="请输入邮箱" bordered={false} />
                        </Form.Item>
                        <Form.Item name="password" rules={[
                            { required: true, message: '请输入密码', },
                            { pattern: new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[A-Za-z0-9]{8,}$/i), message: "密码最低8位英文数字组成" }
                        ]}>
                            <Input.Password className="register-input" placeholder="请输入密码" bordered={false} />
                        </Form.Item>
                        <Form.Item name="passwordRetype" rules={[
                            { required: true, message: '请再次输入密码' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不一致'));
                                },
                            }),
                        ]}>
                            <Input.Password className="register-input" placeholder="再输入密码" bordered={false} />
                        </Form.Item>
                        <Form.Item name="captchaCode" rules={[
                            { required: true, message: '输入验证码' }
                        ]}>
                            <Input className="register-input" placeholder="再输入验证码" suffix={buttonAfter} bordered={false} />
                        </Form.Item >
                        <Form.Item name="inviteCode">
                            <Input className="register-input" placeholder="输入邀请码" bordered={false} />
                        </Form.Item>
                        <Form.Item >
                            <Button type="primary" htmlType="submit" className="register-form-button">
                                立即注册
                            </Button>
                        </Form.Item>
                    </Form>
                </TabPane>
            </Tabs>
            <Row className="register-rule">
                <p>点击"立即注册"即表示同意<a>用户协议</a></p>
            </Row>
            <Row>
                <Col span={12}><a onClick={toLogin}>已有账号？登录</a> </Col>
                <Col span={12} style={{ textAlign: 'right' }}><a>遇到问题？联系客服</a></Col>
            </Row>
            <VerifyBox ref={verifyRef} send={sendCaptcha} />
        </Modal>
    )
}

export default Register